#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>;
using namespace cv;
using namespace std;

int main()
{
//连通域分析  connectedComponents()

    Mat image=imread("/home/lwj/opencv_projeci/1.jpg");
    Mat img,imgv,immg;
    cvtColor(image,img,COLOR_BGR2GRAY);//灰度化
    threshold(img,imgv,50,255,THRESH_BINARY);//二值化
    int num=connectedComponents(imgv,immg);//统计连通域个数
    RNG rng(1);
    vector<Vec3b>colors;
    for(int i=0;i<num;i++)
    {
        //使用均匀分布随机数确定颜色
        Vec3b vec3=Vec3b(rng.uniform(0,256),rng.uniform(0,256),rng.uniform(0,256));
        colors.push_back(vec3);
    }
    Mat  result =Mat::zeros(image.size(),image.type());
    int w=result.cols;
    int h=result.rows;
    for(int row=0;row<h;row++)
    {
        for(int col=0;col<w;col++)
        {
            int label=immg.at<uint16_t>(row,col);//从immg中获取标记的连通域的像素
            if (label==0)
            {
                continue;
            }
            result.at<Vec3b>(row,col)=colors[label];
        }
    }

    imshow("原图",image);
    imshow("标记后图像",result);
    waitKey(0);
    return 0;
}